package com.eatme.core.queue;

import com.eatme.core.array.Array;

import java.util.Random;

public class ArrayQueue<E> implements Queue<E> {

    private Array<E> array;

    public  ArrayQueue(int capacity) {
        array = new Array<>(capacity);

    }

    public  ArrayQueue() {
        array = new Array<>();
    }

    @Override
    public int getSize() {
        return array.getSize();
    }

    @Override
    public boolean isEmpty() {
        return array.isEmpty();
    }

    public int getCapacity() {
        return array.getCapacity();
    }

    @Override
    public void enqueue(E e) {
        array.addLast(e);
    }

    @Override
    public E dequeue() {
        return array.removeFirst();
    }

    @Override
    public E getFront() {
        return array.getFirst();
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("ArrayQueue: ");
        stringBuilder.append("front [");
        for (int i = 0; i < array.getSize(); i++) {
            stringBuilder.append(array.get(i));
            if (i!=array.getSize()-1)
                stringBuilder.append(", ");
        }
        stringBuilder.append("] tail");
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        ArrayQueue<Integer> arrayQueue = new ArrayQueue<>();
        for (int i = 0; i < 10; i++) {
            arrayQueue.enqueue(i);
            System.out.println(arrayQueue);
            if (i % 3 == 2) {
                arrayQueue.dequeue();
                System.out.println(arrayQueue);
            }
        }

        int opCount = 100000;
        ArrayQueue<Integer> arrayQueue1 = new ArrayQueue<>();
        double time1 = testQueue(arrayQueue1,opCount);
        System.out.println("ArrayQueue, time: \t\t" +time1+" s");
        LoopQueue<Integer> loopQueue = new LoopQueue<>();
        double time2 =testQueue(loopQueue,opCount);
        System.out.println("LoopQueue, time: \t\t" +time2+" s");

        LinkedListQueue<Integer> linkedListQueue = new LinkedListQueue<>();
        double time3 =testQueue(linkedListQueue,opCount);
        System.out.println("LinkedListQueue, time: \t" +time3+" s");
    }

    // 测试运行实用opCount个enqueue和dequeue操作的时间，单位：秒
    private static double testQueue(Queue<Integer> queue,int opCount) {
        long startTime =  System.nanoTime();
        Random random = new Random();
        // ...
        for (int i = 0; i < opCount; i++) {
            queue.enqueue(random.nextInt(Integer.MAX_VALUE));
        }
        for (int i = 0; i < opCount; i++) {
            queue.dequeue();
        }
        long endTime = System.nanoTime();
        return (endTime-startTime)/ 1000000000.0;
    }
}
